package com.example.logisticsingle.authorization;


import com.example.logisticsingle.entity.SSOUser;
import com.example.logisticsingle.utils.SSOTokenLoginHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Token认证校验
 *
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private IAMUserDetailsService userDetailsService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        SSOUser user = SSOTokenLoginHelper.loginCheck(request, response);
        if(null!=user) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(user.getUsername());
            //可以校验token和username是否有效，目前由于token对应username存在redis，都以默认都是有效的
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                    request));
            logger.info("authenticated user " + user.getUsername() + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }
}
